<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="耗材类型" prop="type">
        <el-select v-model="queryParams.type" @change="handleQuery" placeholder="请选择…" clearable>
          <el-option v-for="obj in types" :key="obj.value" :label="obj.name" :value="obj.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="耗材编号" prop="no">
        <el-input v-model="queryParams.no" placeholder="请输入耗材编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否分配" prop="fp">
        <el-select v-model="queryParams.fp" @change="handleQuery" placeholder="请选择…" clearable>
          <el-option label="未分配" value="0" />
          <el-option label="已分配" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="代理商" prop="agentId">
        <el-select v-model="queryParams.agentId" placeholder="请选择代理商" clearable filterable @change="handleQuery">
          <el-option v-for="data in agentOptions" :key="data.value" :label="data.label" :value="data.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['consumables:info:add']" >单个新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleBatchOperate('add')" v-hasPermi="['consumables:info:add']" >号段新增</el-button>
      </el-col>
      <!--
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['consumables:info:import']" >表格导入</el-button>
      </el-col>
      -->
      <el-col :span="1.5" v-show="change.type === ''">
        <el-button type="primary" plain icon="el-icon-edit" size="mini" @click="handleBtn('distribution')" v-hasPermi="['consumables:info:distribution']">选择分配</el-button>
      </el-col>
      <el-col :span="1.5" v-show="change.type === ''">
        <el-button type="danger" plain icon="el-icon-refresh" size="mini" @click="handleBtn('recovery')" v-hasPermi="['consumables:info:recovery']" >选择回收</el-button>
      </el-col>
      <el-col :span="1.5" v-show="change.type !== ''">
        <el-button type="success" plain icon="el-icon-check" @click="handleChange" :disabled="multiple" size="mini">确定</el-button>
      </el-col>
      <el-col :span="1.5" v-show="change.type !== ''">
        <el-button plain icon="el-icon-close" size="mini" @click="handleChangeCancel" >取消</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-edit" @click="handleBatchOperate('distribution')" size="mini" v-hasPermi="['consumables:info:distribution']" >号段分配</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-refresh" @click="handleBatchOperate('recovery')" size="mini" v-hasPermi="['consumables:info:recovery']" >号段回收</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['consumables:info:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" ref="consumablesTable" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column v-if="change.type !== ''" type="selection" :selectable="isSelectable" width="55" align="center" />
      <el-table-column label="耗材编号" align="center" prop="serialNumber" />
      <el-table-column label="耗材类型" align="center" prop="equipmentType" >
        <template slot-scope="scope">
          <span v-for="obj in types" :key="obj.value">
            <span v-if="obj.value === scope.row.equipmentType"> {{ obj.name }} </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否分配" align="center" prop="distributeFlag" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.distributeFlag === '0'" size="mini" type="info">未分配</el-tag>
          <el-tag v-if="scope.row.distributeFlag === '1'" size="mini" type="success">已分配</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分配代理商" align="center" prop="agentName" />
      <el-table-column label="使用状态" align="center" prop="isUse" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isUse === '0'" size="mini" type="success">未使用</el-tag>
          <el-tag v-if="scope.row.isUse === '1'" size="mini" type="info">已使用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用时段" align="center" prop="isUse" >
        <template slot-scope="scope">
          <span v-if="scope.row.isUse === '1'">
            {{scope.row.useStartTime +"至" + scope.row.useEndTime}}
          </span>
          <br />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     :disabled="!(scope.row.distributeFlag === '0' && scope.row.isUse === '0')" v-hasPermi="['consumables:info:remove']" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加耗材信息对话框 -->
    <el-dialog title="添加耗材信息" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="耗材类型" prop="equipmentType">
          <el-select v-model="form.equipmentType" placeholder="请选择耗材类型" style="width: 100%;">
            <el-option v-for="obj in types" :key="obj.value" :label="obj.name" :value="obj.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="耗材编号" prop="serialNumber">
          <el-input v-model="form.serialNumber" placeholder="请输入耗材编号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 通过号段操作耗材信息对话框 -->
    <el-dialog :title="batchOperateDialogTitle" :visible.sync="batchOperateOpen" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="batchOperateForm" :model="batchOperateForm" :rules="batchOperateFormRules" label-width="80px">
        <el-form-item label="耗材类型" prop="equipmentType">
          <el-select v-model="batchOperateForm.equipmentType" placeholder="请选择耗材类型" style="width: 100%;">
            <el-option v-for="obj in types" :key="obj.value" :label="obj.name" :value="obj.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产日期" prop="date">
          <el-date-picker v-model="batchOperateForm.date" type="date"
                          value-format="yyyy-MM-dd" placeholder="请选择生产日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="开始序号" prop="start">
          <el-input-number v-model="batchOperateForm.start" :min="0" placeholder="请输入号段开始序号"></el-input-number>
        </el-form-item>
        <el-form-item label="结束序号" prop="end">
          <el-input-number v-model="batchOperateForm.end" :min="1" :max="9999" placeholder="请输入号段结束序号"></el-input-number>
        </el-form-item>
        <el-form-item v-if="batchOperateType === 'distribution'" label="代理商" prop="agentId">
          <el-select v-model="batchOperateForm.agentId" placeholder="请选择代理商" filterable style="width: 100%;">
            <el-option v-for="data in agentOptions" :key="data.value" :label="data.label" :value="data.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="! batchOperateLoading" type="primary" @click="submitBatchOperate">确 定</el-button>
        <el-button v-if="batchOperateLoading" :loading="true" type="primary"> 执行中</el-button>
        <el-button @click="cancelBatchOperate">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 耗材导入对话框 -->
    <el-dialog title="耗材导入" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls"
        :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 耗材分配 -->
    <el-dialog title="分配耗材" :visible.sync="change.open" width="400px" append-to-body :close-on-click-modal="false">
      <el-form ref="distributionForm" :model="change.form" :rules="change.rules" label-width="80px">
        <el-form-item label="代理商" prop="agentId">
          <el-select v-model="change.form.agentId" placeholder="请选择代理商" filterable style="width: 100%;">
            <el-option v-for="data in change.agentOptions" :key="data.value" :label="data.label" :value="data.value" />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDistributionForm">确 定</el-button>
        <el-button @click="distributionCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInfo,
  delInfo,
  addInfo,
  reqDistribution,
  reqRecovery, batchOperateInfo
} from "@/api/business/consumables";
import {getToken} from "@/utils/auth";
import {getOptionData} from "@/api/business/agent";

export default {
  name: "ConsumablesInfo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      infos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 耗材信息表格数据
      infoList: [],
      // 是否显示弹出层
      open: false,
      // 耗材类型
      types: [
        {value:"1", name:"一次性体温传感器"},
        {value:"2", name:"一次性心电电极贴"}
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        no: null,
        type: null,
        fp: null,
        agentId: null,
      },
      // 代理商下拉数据
      agentOptions: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        equipmentType: [
          { required: true, message: "耗材类型不能为空", trigger: "blur" }
        ],
        serialNumber: [
          { required: true, message: "耗材编号不能为空", trigger: "blur" }
        ],
      },

      // 号段批量操作弹框显示
      batchOperateOpen: false,
      // 号段批量操作弹框标题
      batchOperateDialogTitle: '',
      // 号段批量操作类型
      batchOperateType: '',
      // 号段批量操作表单参数
      batchOperateForm: {},
      // 号段批量操作表单校验
      batchOperateFormRules: {
        equipmentType: [
          { required: true, message: "耗材类型不能为空", trigger: "blur" }
        ],
        start: [
          { required: true, message: "开始序号不能为空", trigger: "blur" }
        ],
        end: [
          { required: true, message: "结束序号不能为空", trigger: "blur" }
        ],
        date: [
          { required: true, message: "生产日期不能为空", trigger: "blur" }
        ],
      },
      batchOperateLoading: false,

      // 耗材导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/consumables/info/importData"
      },

      // 耗材分配与回收相关参数
      change: {
        // 类型
        type: '',
        // 弹框
        open: false,
        // 代理商下拉数据
        agentOptions: [],
        temperatureSensorArr: [],
        ecgElectrodeArr: [],
        // 表单信息
        form: {},
        // 表单校验
        rules: {},
      },
    };
  },
  created() {
    this.getAgentData();
    this.getList();
  },
  methods: {
    getAgentData (){
      getOptionData().then(response => {
        this.agentOptions = response.data;
      });
    },
    /** 查询耗材信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serialNumber: null,
        equipmentType: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.infos = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addInfo(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('该操作不可撤销，是否确认删除所选耗材？').then(function() {
        return delInfo(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('consumables/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('consumables/info/importTemplate', {
      }, `耗材导入模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 分配（type = distribution）
    // 回收（type = recovery）
    handleBtn(type){
      this.change.type = type;
    },
    isSelectable(row, index) {
      if(this.change.type === "distribution") {
        return row.distributeFlag === "0";
      }
      if(this.change.type === "recovery") {
        // 只回收已分配且未使用的耗材
        return row.distributeFlag === "1" && row.isUse === '0';
      }
      return false;
    },
    handleChange(){
      if(this.change.type === "distribution") {
        this.change.temperatureSensorArr = [];
        this.change.ecgElectrodeArr = [];
        // 体温传感器
        let tw = [];
        // 心电电极片
        let xd = [];
        for(let i = 0; i < this.infos.length; i++) {
          let info = this.infos[i];
          if(info.equipmentType === "1") {
            tw.push(info.serialNumber);
            this.change.temperatureSensorArr.push(info.id);
          }
          if(info.equipmentType === "2") {
            xd.push(info.serialNumber);
            this.change.ecgElectrodeArr.push(info.id);
          }
        }

        let msg = "是否确认分配以下所选耗材吗？<br/>";
        if(tw.length > 0) {
          msg += "<b>一次性体温传感器：</b>" + tw.join("、") + "<br/>";
        }
        if(xd.length > 0) {
          msg += "<b>一次性心电电极贴：</b>" + xd.join("、") + "<br/>";
        }

        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }).then(() => {
          getOptionData().then(response => {
            this.change.rules = {
              agentId: [
                { required: true, message: "请选择要分配的代理商", trigger: "blur" }
              ]
            }
            this.change.agentOptions = response.data;
            this.resetDistributionForm();
            this.change.open = true;
          });
        }).catch(() => {
        });
      }

      if(this.change.type === "recovery") {
        let ids = [];
        for(let i = 0; i < this.infos.length; i++) {
          let info = this.infos[i];
          ids.push(info.id);
        }
        reqRecovery(ids).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.handleChangeCancel();
          this.getList();
        });
      }
    },
    handleChangeCancel(){
      this.change.type = "";
      this.$refs.consumablesTable.clearSelection();
      this.infos = [];
    },
    submitDistributionForm(){
      this.$refs["distributionForm"].validate(valid => {
        if (valid) {
          // 提交分配
          let param = this.change.form;
          param.twId = this.change.temperatureSensorArr.join(",")
          param.xdId = this.change.ecgElectrodeArr.join(",")

          reqDistribution(param).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.distributionCancel();
            this.handleChangeCancel();
            this.getList();
          });
        }
      });
    },
    distributionCancel(){
      this.change.open = false;
      this.resetDistributionForm();
    },
    resetDistributionForm(){
      this.change.form = {
        agentId: null,
      };
      this.resetForm("distributionForm");
    },

    /** 新增按钮操作 */
    handleBatchOperate(type) {
      this.resetBatchOperate();
      if("add" === type) {
        this.batchOperateDialogTitle = "按号段批量添加";
      }
      if("distribution" === type) {
        this.batchOperateDialogTitle = "按号段批量分配";
        this.batchOperateFormRules.agentId = [
          { required: true, message: "分配代理商不能为空", trigger: "blur" }
        ];
      }
      if("recovery" === type) {
        this.batchOperateDialogTitle = "按号段批量回收";
      }
      this.batchOperateType = type;
      this.batchOperateOpen = true;
    },
    resetBatchOperate() {
      this.batchOperateForm = {
        equipmentType: null,
        date: null,
        start: null,
        end: null,
        agentId: null,
      };
      this.resetForm("batchOperateForm");
    },
    cancelBatchOperate() {
      this.batchOperateOpen = false;
      this.batchOperateLoading = false;
      this.resetBatchOperate();
    },
    submitBatchOperate(){
      let that = this;
      that.$refs["batchOperateForm"].validate(valid => {
        if (valid) {
          let start = that.batchOperateForm.start;
          let end = that.batchOperateForm.end;
          if(start > end) {
            that.$modal.msgWarning("开始序号不能大于结束序号！");
            return ;
          }

          let uri = "";
          let type = that.batchOperateType;
          if("add" === type) {
            uri = "/consumables/info/batchAdd";
          }
          if("distribution" === type) {
            uri = "/consumables/info/batchDistribution";
          }
          if("recovery" === type) {
            uri = "/consumables/info/batchRecovery";
          }

          that.batchOperateLoading = true;
          batchOperateInfo(uri, that.batchOperateForm).then(response => {
            that.batchOperateLoading = false;
            if("add" === type) {
              that.batchAddResult(response.data);
            }
            if("distribution" === type) {
              that.batchDistributionResult(response.data);
            }
            if("recovery" === type) {
              that.batchRecoveryResult(response.data);
            }
          });
        }
      });
    },
    batchAddResult(data) {
      let that = this;
      let success = data.success;
      let exist = data.exist;
      if(success < 1) {
        that.$modal.msgError("新增失败！该号段耗材已全部存在！");
      } else {
        that.$modal.msgSuccess("已成功添加"+success+"条耗材数据！");
        if(exist > 0) {
          let existList = data.existList;
          let msg = "";
          for (let i = 0; i < existList.length; i++) {
            if(msg !== '') {
              msg += "、";
            }
            msg += existList[i];
          }
          that.$modal.notifyWarning("耗材编号："+msg+"已存在，添加失败！");
        }
        that.cancelBatchOperate();
        that.getList();
      }
    },
    batchDistributionResult(data) {
      let that = this;
      let success = data.success;
      let exist = data.exist;
      if(success < 1) {
        that.$modal.msgError("分配失败！该号段耗材已分配或未添加或已使用！");
      } else {
        that.$modal.msgSuccess("已成功分配"+success+"条耗材数据！");
        if(exist > 0) {
          let existList = data.existList;
          let msg = "";
          for (let i = 0; i < existList.length; i++) {
            if(msg !== '') {
              msg += "、";
            }
            msg += existList[i];
          }
          that.$modal.notifyWarning("耗材编号："+msg+"已分配或未添加或已使用，此次分配失败！");
        }
        that.cancelBatchOperate();
        that.getList();
      }
    },
    batchRecoveryResult(data) {
      let that = this;
      let success = data.success;
      let exist = data.exist;
      if(success < 1) {
        that.$modal.msgError("回收失败！该号段耗材未分配或未添加或已使用！");
      } else {
        that.$modal.msgSuccess("已成功回收"+success+"条耗材数据！");
        if(exist > 0) {
          let existList = data.existList;
          let msg = "";
          for (let i = 0; i < existList.length; i++) {
            if(msg !== '') {
              msg += "、";
            }
            msg += existList[i];
          }
          that.$modal.notifyWarning("耗材编号："+msg+"未分配或未添加或已使用，此次回收失败！");
        }
        that.cancelBatchOperate();
        that.getList();
      }
    },
  }
};
</script>
